package com.xuecheng.learning.service.impl;

import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.LearningProgressDto;
import com.xuecheng.commons.model.dto.RecordDto;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.api.ContentClient;
import com.xuecheng.learning.domain.CourseRecord;
import com.xuecheng.learning.mapper.CourseRecordMapper;
import com.xuecheng.learning.service.CourseRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.media.api.MediaClient;
import com.xuecheng.search.api.SearchClient;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;

/**
 * <p>
 * 选课记录 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-12-12
 */
@Service
public class CourseRecordServiceImpl extends ServiceImpl<CourseRecordMapper, CourseRecord> implements CourseRecordService {

    //查询选课记录
    @Override
    public ResponseResult<CourseRecordVo> myCourseRecord(Long coursePubId) {
        //通过ThreadLocal获取登录用户
        Long userId = AuthInfoHolder.getUserId();
        //查询选课记录表
        CourseRecord courseRecord = this.lambdaQuery().eq(CourseRecord::getCoursePubId, coursePubId)
                .eq(CourseRecord::getUserId, userId)
                .one();
        //判断当前用户是否有选课记录
        if (courseRecord!=null){
            //转为vo
            CourseRecordVo courseRecordVo = BeanHelper.copyProperties(courseRecord, CourseRecordVo.class);
            return ResponseResult.okResult(courseRecordVo);
        }else {
            //没有选课记录直接放行
            return ResponseResult.okResult();
        }
    }

    @Autowired
    private SearchClient searchClient;//搜索feign

    //用户支付成功，保存选课记录
    @Override
    public ResponseResult saveRecord(RecordDto recordDto) throws IOException {
        //查询选课记录
        CourseRecord courseRecord = this.lambdaQuery().eq(CourseRecord::getUserId, recordDto.getUserId())
                .eq(CourseRecord::getCoursePubId, recordDto.getCoursePubId())
                .one();
        if (courseRecord!=null){
            //之前已上过收费课程的免费部分
            courseRecord.setPaid(1);//已支付
            this.updateById(courseRecord);
        }else {
            //新用户
            courseRecord =new CourseRecord();
            //获取课程详情
            ResponseResult<CoursePubIndexVo> responseResult = searchClient.findById(recordDto.getCoursePubId().toString());
            //判断feign调用是否成功
            if (responseResult.getCode()!=0){
                throw new BusinessException(ErrorCode.NOTFOUND);
            }
            //获取调用结果
            CoursePubIndexVo coursePubIndexVo = responseResult.getData();
            //封装选课记录
            courseRecord.setUserId(recordDto.getUserId()); // 购买用户id
            courseRecord.setCompanyId(coursePubIndexVo.getCompanyId()); // 课程机构id
            courseRecord.setCourseId(coursePubIndexVo.getCourseId()); // 课程id
            courseRecord.setCoursePubId(coursePubIndexVo.getCourseId());// 课程发布id
            courseRecord.setCoursePubName(coursePubIndexVo.getName()); // 课程名
            courseRecord.setTeachmode(coursePubIndexVo.getTeachmode()); // 教学模式
            courseRecord.setCreateDate(new Date()); // 创建时间
            courseRecord.setPaid(1); // 已支付
            //保存数据库
            this.save(courseRecord);
        }
        return ResponseResult.okResult();
    }

    @Autowired
    private ContentClient contentClient;

    @Autowired
    private MediaClient mediaClient;

    //课程详情获取媒资地址
    @Override
    public ResponseResult<ResourceVo> resourceUrl(Long coursePubId, Long mediaId, Long teachplanId) throws Exception {
        //查询该课程信息
        ResponseResult<CoursePubVo> coursePubVoResponseResult = contentClient.findById(coursePubId);
        //判断课程feign是否调用成功
        if (coursePubVoResponseResult.getCode()!=0){
            throw new BusinessException(ErrorCode.NOTFOUND);
        }
        CoursePubVo coursePubVo = coursePubVoResponseResult.getData();
        //是否为收费课程
        if (coursePubVo.getCharge().equals(CourseConstants.CHARGE_YES)){
            //是收费课程，查询该用户是否已购买
            CourseRecord courseRecord = this.lambdaQuery()
                    .eq(CourseRecord::getUserId, AuthInfoHolder.getUserId())
                    .eq(CourseRecord::getCourseId, coursePubId)
                    .one();
            //判断支付状态
            if (courseRecord==null || courseRecord.getPaid() !=1){
                //无购买成功记录，判断此课程是否支持试学
                ResponseResult<TeachplanVo> teachplanVoResponseResult = contentClient.findTeachplanById(teachplanId);
                //判断课程计划feign调用是否成功
                if (teachplanVoResponseResult.getCode()!=0){
                    throw new BusinessException(ErrorCode.NOTFOUND);
                }
                //获取课程计划
                TeachplanVo teachplanVo = teachplanVoResponseResult.getData();
                if (teachplanVo.getIsPreview().equals("0")){
                    //不支持试学
                    throw new BusinessException(ErrorCode.NOTPLAY);
                }
            }
        }
        //返回播放地址（免费课程、支持试学课程、已付费课程）
        return mediaClient.mediaUrl(mediaId);
    }

    @Override
    public ResponseResult progress(LearningProgressDto progressDto) throws IOException {
        //查询选课记录
        //获取登录人id
        Long userId = AuthInfoHolder.getUserId();
        CourseRecord courseRecord = this.lambdaQuery()
                .eq(CourseRecord::getUserId, userId)
                .eq(CourseRecord::getCourseId, progressDto.getCoursePubId())
                .one();
        if (courseRecord!=null){
            //原先就有的，更新进度
            courseRecord.setTeachplanId(progressDto.getTeachPlanId());
            courseRecord.setTeachplanName(progressDto.getTeachPlanName());
            //更新数据库
            this.updateById(courseRecord);
        }else {
            //第一次选课，新增记录
            //查询课程基本信息
            ResponseResult<CoursePubIndexVo> responseResult = searchClient.findById(progressDto.getCoursePubId().toString());
            //判断searchFeign调用是否成功
            if (responseResult.getCode()!=0){
                throw new BusinessException(ErrorCode.NOTFOUND);
            }
            CoursePubIndexVo coursePubIndexVo = responseResult.getData();
            //封装选课记录
            CourseRecord courseRecordNew = new CourseRecord();
            courseRecordNew.setUserId(userId); // 购买人id
            courseRecordNew.setCompanyId(coursePubIndexVo.getCompanyId()); // 课程机构id
            courseRecordNew.setCourseId(coursePubIndexVo.getCourseId()); // 课程id
            courseRecordNew.setCoursePubId(coursePubIndexVo.getCourseId());// 课程发布id
            courseRecordNew.setCoursePubName(coursePubIndexVo.getName()); // 课程名
            courseRecordNew.setTeachmode(coursePubIndexVo.getTeachmode()); // 教学模式
            courseRecordNew.setCreateDate(new Date()); // 创建时间
            courseRecordNew.setTeachplanId(progressDto.getTeachPlanId()); // 课程计划id
            courseRecordNew.setTeachplanName(progressDto.getTeachPlanName()); // 课程计划名称

            //保存课程选课记录
            this.save(courseRecordNew);
        }
        return ResponseResult.okResult();
    }
}
